 /*
    MegaShorter, the ultimate url-shorting tool
    Copyright (C) 2011  Ivan I. Kolesnikov

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "jmpshorter.h"

QSharedPointer<Shorter> JMpShorterCreator::create(QSharedPointer<QSettings> settings)
{
    return QSharedPointer<Shorter>(new JMpShorter(settings), &QObject::deleteLater);
}

JMpShorter::JMpShorter(QSharedPointer<QSettings> s, QObject *parent) :
    Shorter(s, parent)
{
    setName("J.mp");
    setShorterSite(QUrl("http://j.mp/"));
}

void JMpShorter::doShortLink(const QUrl &url)
{
    settings->beginGroup("JMpShorter");
    QString login = settings->value("login").toString();
    QString apiKey = settings->value("apiKey").toString();
    settings->endGroup();

    if (login.isEmpty() || apiKey.isEmpty())
    {
        emit done(Shorter::Error,"","Please set \"login\" and \"apiKey\" options in config");
        return;
    }

    QUrl reqUrl("http://api.j.mp/v3/shorten");

    reqUrl.addQueryItem("login",login);
    reqUrl.addQueryItem("apiKey",apiKey);
    reqUrl.addQueryItem("longUrl",url.toString());
    reqUrl.addQueryItem("format","txt");

    QNetworkReply *r = manager()->get(QNetworkRequest(reqUrl));
    applyAttribute(r, url);
}

void JMpShorter::doFinish(QNetworkReply *reply)
{
    QString s(reply->readAll());

    if (reply->error() != QNetworkReply::NoError)
        emit done(Shorter::Error,"",reply->errorString());
    else
        emit done(Shorter::Ok,getAttribute(reply),s.trimmed());
}

